package service.impl;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import javax.annotation.Resource;
import javax.jms.Connection;
import javax.jms.ConnectionFactory;
import javax.jms.Destination;
import javax.jms.JMSException;
import javax.jms.MessageConsumer;
import javax.jms.Session;
import javax.jms.TextMessage;





import org.json.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import dao.UserDao;
import service.UserManager;
import vo.Log;
import vo.Student;
@Service("sm")
public class UserManagerImpl implements UserManager {
	@Autowired(required=true)
	private UserDao sd;
	@Resource(name="queueDestination")
	private Destination queue;
	@Resource(name="targetConnectionFactory")
	private ConnectionFactory factory;
	@Override
	@Transactional
	public List<Log> log(){
		Connection con;
		List<Log> logs = new ArrayList<Log>();
		Log lg = null;
		try {
			con = factory.createConnection();                   
			con.start();
			System.out.println(con);
			
			Session sen = con.createSession(false, Session.AUTO_ACKNOWLEDGE);
			
			MessageConsumer consumer = sen.createConsumer(queue);
			
			TextMessage msg = (TextMessage) consumer.receive();
			System.out.println(msg.getText());
			JSONObject json;
			try {
				json = new JSONObject(msg.getText());
				lg = new Log();
				lg.setIp(json.getString("ip"));
				lg.setUname(json.getString("uname"));
				lg.setTime((Date) new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").parse(json.getString("time")));
				System.out.println(lg.toString());
				sd.addLog(lg);
				logs = sd.findLog();
				
			} catch (Exception e1) {
				// TODO Auto-generated catch block 
				e1.printStackTrace();
			}
			consumer.close();
			sen.close();
			con.close();
		} catch (JMSException e1) {
			// TODO Auto-generated catch block
			e1.printStackTrace();
		}
		
		return logs;
	}
	
	
	@Override
	@Transactional
	public int showLog(Log lg) {
		// TODO Auto-generated method stub
		return sd.addLog(lg);
	}
	
	
	
	
	
	/*@Override
	public Student login(String uname, String psd) {
		System.out.println(psd);
		return null;
	}
	@Override
	@Transactional
	public int regist(Student s) {
		System.out.println(s.getPsd());
		//s.setPsd(BaseUtil.JohnMd(s.getPsd(), "md5"));
		return sd.addStu(s);
	}*/


}
